package com.moussa.mike;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnDismissListener;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemLongClickListener;

public class MainActivity extends ListActivity {

	private List<YouTubeVideo> mVideos = new ArrayList<YouTubeVideo>();
	private String TAG = "YouTubeAccess";

	private final int REQUEST_VIDEO = 100;
	private final int REQUEST_CHANNEL = 101;
	private final int MENU_SHARE = Menu.FIRST;
	private final int MENU_VIEW_VIDEO = Menu.FIRST + 1;
	private final int MENU_VIEW_AUTHOR_CHANNEL = Menu.FIRST + 2;
	private int _id;
	private String query;
	private Handler mHandler = new Handler();
	private Intent intent;
	private ProgressDialog progressDialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		intent = getIntent();
		if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
			query = intent.getStringExtra(SearchManager.QUERY);
			searchVideos();
		}

		ListView listView = getListView();
		registerForContextMenu(listView);
		listView.setOnItemLongClickListener(new OnItemLongClickListener(){

			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				_id = arg2;
				return false;
			}

		});	

	}



	@Override
	protected void onPostResume() {
		// TODO Auto-generated method stub
		super.onPostResume();

		if (!Intent.ACTION_SEARCH.equals(intent.getAction())) {


			mHandler.postDelayed(new Runnable(){

				@Override
				public void run() {
					startSearch(null, false, null, false);
				} 

			},
			300);

		}
	}



	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		return super.onKeyDown(keyCode, event);
	}



	Thread searchThread = new Thread(new Runnable(){

		public void run() {	

			mVideos = YouTubeSearchAPI.doSearch(query, 10);

			MainActivity.this.runOnUiThread(new Runnable(){

				@Override
				public void run() {
					if(progressDialog!=null && progressDialog.isShowing())
						progressDialog.dismiss();
					if (mVideos == null)
					{
						new AlertDialog.Builder(MainActivity.this)
						.setTitle("Cannot connect to YouTube")
						.setMessage("Please make sure you have an internet connection")
						.setIcon(android.R.drawable.ic_dialog_alert)
						.show();
					}	
					else
					{
						if (mVideos.size() == 0)
						{
							new AlertDialog.Builder(MainActivity.this)
							.setTitle("No Results")
							.setMessage("Please try a different search term")
							.setIcon(android.R.drawable.ic_dialog_alert)
							.show();
						}
						YouTubeAdapter adapter = new YouTubeAdapter(MainActivity.this, R.layout.main,mVideos);
						getListView().setAdapter(adapter);
					}

				}

			});
		}

	});

	private void showProgressDialog(){
		progressDialog = new ProgressDialog(this);
		progressDialog.setTitle("Please wait...");
		progressDialog.setMessage("Searching for videos.");
		progressDialog.setIndeterminate(true);
		progressDialog.setCancelable(true);
		progressDialog.setOnDismissListener(new OnDismissListener() {

			public void onDismiss(DialogInterface dialog) {
				dialog.dismiss();

			}

		});
		progressDialog.setOnCancelListener(new OnCancelListener() {

			public void onCancel(DialogInterface arg0) {
				// TODO cleaning of any opened thread
				arg0.dismiss();
			}

		});
		progressDialog.show();
	}

	private void searchVideos()
	{
		showProgressDialog();
		mHandler.postDelayed(new Runnable(){

			@Override
			public void run() {
				searchThread.run();
			}
		},500);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Log.d(TAG,"item clicked:" + position);
		Intent intent = mVideos.get(position).getVideoIntent();
		startActivityForResult(intent, REQUEST_VIDEO);
		super.onListItemClick(l, v, position, id);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		menu.add(MENU_SHARE, MENU_SHARE,0,"Share this video");
		menu.add(MENU_VIEW_VIDEO, MENU_VIEW_VIDEO,0,"Watch this video");
		menu.add(MENU_VIEW_AUTHOR_CHANNEL, MENU_VIEW_AUTHOR_CHANNEL,0,"View author's channel");
		menu.setHeaderTitle("More options:");
		menu.setHeaderIcon(android.R.drawable.ic_dialog_info);
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {

		switch(item.getItemId()){
		case MENU_SHARE: 
			String data = mVideos.get(_id).getUrl();
			Intent shareIntent = new Intent();
			shareIntent.setAction(Intent.ACTION_SEND);
			shareIntent.setType("text/plain");
			shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Hey check this awesome video out!");
			shareIntent.putExtra(Intent.EXTRA_TEXT, data);
			startActivity(Intent.createChooser(shareIntent,"Share with:"));
			break;
		case MENU_VIEW_VIDEO: 
			startActivityForResult(mVideos.get(_id).getVideoIntent(), REQUEST_VIDEO);
			break;
		case MENU_VIEW_AUTHOR_CHANNEL: 
			startActivityForResult(mVideos.get(_id).getChannelIntent(), REQUEST_CHANNEL);
			break;
		}

		return super.onContextItemSelected(item);
	}


}